package cc.openkit.kitcommon;

import cc.openkit.exception.MyException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;

/**
 * 很多测试内容
 */
public class KitUtil {

    /**
     * signature 的加密算法
     */
    public static boolean signatureIsTrue(Map<String, String> param,String  timestamp, String appkey, String signature) {
        String s = mapSortedByKey(param);  // 排序拼接
        s = s + timestamp.replaceAll(" ", "");  // 加密前的所有字符串
        String s265;  // 加密后端字符串
        try {
            s265 = HMACSHA256(s, appkey);
        } catch (Exception e) {
            e.printStackTrace();
            // 处理异常
            throw new MyException("非法签名");
        }
        return signature.equals(s265);
    }

    /**
     * 根据MAP中的 KEY 的升序排序
     */
    public static String mapSortedByKey(Map<String, String> param) {
        StringBuilder stringBuilder = new StringBuilder();
        ArrayList<String> keyList = new ArrayList<>(param.keySet());
        Collections.sort(keyList);
        for (int i = 0; i < keyList.size(); i++) {
            String key = keyList.get(i);
            if (i == keyList.size() - 1) {
                stringBuilder.append(key).append("=").append(param.getOrDefault(key, ""));
            } else {
                stringBuilder.append(key).append("=").append(param.getOrDefault(key, "")).append("&");
            }
        }
        return stringBuilder.toString();
    }

    /**
     * HMACSHA256 加密
     * data要加密的数据，key密钥
     */
    public static String HMACSHA256(String data, String key) throws Exception {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();

    }


}
